<template>
  <div>
    <h2>邮箱账号</h2>

    <div class="toolbar">
      <button @click="startCreate">新增账号</button>
      <p class="tip">用于 IMAP 拉取与 SMTP 发送。建议为每个业务邮箱单独配置。</p>
    </div>

    <table class="table" v-if="list.length">
      <thead>
      <tr>
        <th>用户名</th>
        <th>IMAP</th>
        <th>SMTP</th>
        <th>SSL/TLS</th>
        <th>启用</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="it in list" :key="it.id">
        <td>{{ it.username }}</td>
        <td>{{ it.imapHost }}:{{ it.imapPort || (it.imapSsl ? 993 : 143) }}</td>
        <td>{{ it.smtpHost }}:{{ it.smtpPort || (it.smtpSsl ? 465 : (it.smtpStarttls ? 587 : 25)) }}</td>
        <td>
          IMAP: {{ it.imapSsl ? 'SSL' : '—' }} /
          SMTP: <span v-if="it.smtpSsl">SSL</span><span v-else-if="it.smtpStarttls">STARTTLS</span><span v-else>—</span>
        </td>
        <td>{{ it.enabled ? '是' : '否' }}</td>
        <td class="ops">
          <button @click="test(it)">测试连通</button>
          <button @click="startEdit(it)">编辑</button>
          <button class="danger" @click="del(it)">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <p v-else class="muted">暂无账号，点击“新增账号”开始配置。</p>

    <!-- 表单 -->
    <div v-if="editing" class="panel">
      <h3>{{ form.id ? '编辑账号' : '新增账号' }}</h3>
      <form @submit.prevent="save" class="form two-col">
        <div class="field">
          <label>用户名（邮箱地址）</label>
          <input v-model.trim="form.username" placeholder="例如：robot@example.com" required />
        </div>
        <div class="field">
          <label>密码/授权码</label>
          <input v-model="form.password" type="password" :placeholder="form.id ? '留空则不修改' : '请输入密码或授权码'" :required="!form.id" />
        </div>

        <div class="field">
          <label>IMAP 主机</label>
          <input v-model.trim="form.imapHost" placeholder="imap.example.com" required />
        </div>
        <div class="field">
          <label>IMAP 端口</label>
          <input v-model.number="form.imapPort" type="number" placeholder="993/143" />
        </div>
        <div class="field">
          <label>IMAP SSL</label>
          <select v-model="form.imapSsl">
            <option :value="true">开启</option>
            <option :value="false">关闭</option>
          </select>
        </div>

        <div class="field">
          <label>SMTP 主机</label>
          <input v-model.trim="form.smtpHost" placeholder="smtp.example.com" required />
        </div>
        <div class="field">
          <label>SMTP 端口</label>
          <input v-model.number="form.smtpPort" type="number" placeholder="465/587/25" />
        </div>
        <div class="field">
          <label>SMTP SSL</label>
          <select v-model="form.smtpSsl">
            <option :value="true">开启(465)</option>
            <option :value="false">关闭</option>
          </select>
        </div>
        <div class="field">
          <label>SMTP STARTTLS</label>
          <select v-model="form.smtpStarttls">
            <option :value="true">开启(587)</option>
            <option :value="false">关闭</option>
          </select>
        </div>

        <div class="field">
          <label>启用</label>
          <select v-model="form.enabled">
            <option :value="true">是</option>
            <option :value="false">否</option>
          </select>
        </div>

        <div class="actions">
          <button :disabled="loading">{{ form.id ? '保存修改' : '创建' }}</button>
          <button type="button" class="plain" @click="cancel">取消</button>
        </div>

        <p class="ok" v-if="ok">{{ ok }}</p>
        <p class="err" v-if="err">{{ err }}</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { accountApi } from '@/api/account'

const list = ref([])
const editing = ref(false)
const loading = ref(false)
const ok = ref(''); const err = ref('')

const emptyForm = () => ({
  id: null, username: '',
  password: '',
  imapHost: '', imapPort: null, imapSsl: true,
  smtpHost: '', smtpPort: null, smtpSsl: true, smtpStarttls: false,
  enabled: true
})
const form = reactive(emptyForm())

const load = async () => {
  try { list.value = await accountApi.listMailAcc() } catch(e){ console.warn(e); list.value=[] }
}
onMounted(load)

const startCreate = () => { Object.assign(form, emptyForm()); editing.value = true; ok.value=''; err.value='' }
const startEdit = (it) => {
  Object.assign(form, {
    id: it.id, username: it.username,
    password: '',
    imapHost: it.imapHost, imapPort: it.imapPort, imapSsl: !!it.imapSsl,
    smtpHost: it.smtpHost, smtpPort: it.smtpPort, smtpSsl: !!it.smtpSsl, smtpStarttls: !!it.smtpStarttls,
    enabled: !!it.enabled
  })
  editing.value = true; ok.value=''; err.value=''
}
const cancel = () => { editing.value = false }

const save = async () => {
  loading.value = true; ok.value=''; err.value=''
  try {
    const payload = { ...form }
    if (!payload.password) delete payload.password // 编辑时留空不改
    if (payload.id) await accountApi.updateMailAcc(payload.id, payload)
    else await accountApi.createMailAcc(payload)
    ok.value = '保存成功'
    await load()
    editing.value = false
  } catch (e) {
    err.value = e?.response?.data?.message || '保存失败'
  } finally {
    loading.value = false
  }
}

const del = async (it) => {
  if (!confirm(`确定删除账号 ${it.username} 吗？`)) return
  try { await accountApi.deleteMailAcc(it.id); await load() } catch(e){ alert(e?.response?.data?.message || '删除失败') }
}

const test = async (it) => {
  try {
    const r = await accountApi.testMailAcc(it.id)
    alert(r?.message || '连接正常')
  } catch (e) {
    alert(e?.response?.data?.message || '连接失败')
  }
}
</script>

<style scoped>
.toolbar{display:flex;align-items:center;gap:12px;margin-bottom:12px}
.tip{color:#6b7280}
.table{width:100%;border-collapse:collapse;margin-top:8px}
.table th,.table td{border:1px solid #eee;padding:8px}
.ops button{margin-right:8px}
button{padding:6px 10px;border:1px solid #409eff;background:#409eff;color:#fff;border-radius:8px}
button.plain{background:#fff;color:#374151;border-color:#e5e7eb}
button.danger{background:#ef4444;border-color:#ef4444}
.panel{margin-top:16px;background:#fff;border:1px solid #eee;border-radius:8px;padding:16px}
.form{display:grid;gap:8px;max-width:900px}
.form.two-col{grid-template-columns:repeat(2, minmax(260px, 1fr)); column-gap:16px}
.field{display:flex;flex-direction:column}
input,select{background:#f7f8fb;border:1px solid #e5e7eb;border-radius:8px;padding:6px 8px}
.actions{grid-column:1 / -1;display:flex;gap:8px;margin-top:8px}
.ok{color:#16a34a}.err{color:#dc2626}
</style>
